<template>
  <div class="dictionary-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>领域词典</h3>
          <el-button v-if="userStore.isAdmin" type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加词条
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索名称或释义..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-select
            v-model="filterCategory"
            placeholder="筛选类别"
            clearable
            style="width: 100%"
            @change="handleSearch"
          >
            <el-option label="全部类别" value="" />
            <el-option
              v-for="cat in categories"
              :key="cat"
              :label="cat"
              :value="cat"
            />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-statistic title="词条总数" :value="totalCount" />
        </el-col>
      </el-row>

      <!-- 词典表格 -->
      <el-table
        :data="displayedTerms"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="term" label="名称" width="200" />
        <el-table-column prop="category" label="类别" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">
              {{ row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="definition" label="释义" show-overflow-tooltip />
        <el-table-column v-if="userStore.isAdmin" label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="totalCount > pageSize"
        style="margin-top: 20px; justify-content: center"
        layout="prev, pager, next"
        :total="totalCount"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 添加/编辑词条对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑词条' : '添加词条'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="termForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="term">
          <el-input v-model="termForm.term" placeholder="请输入专业术语名称" />
        </el-form-item>

        <el-form-item label="类别" prop="category">
          <el-select
            v-model="termForm.category"
            placeholder="选择或输入新类别"
            allow-create
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="cat in categories"
              :key="cat"
              :label="cat"
              :value="cat"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="释义" prop="definition">
          <el-input
            v-model="termForm.definition"
            type="textarea"
            :rows="6"
            placeholder="请输入术语的释义或定义"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEditing ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import api from '../api'
import { useUserStore } from '../store'

const userStore = useUserStore()

// 数据
const terms = ref([])
const loading = ref(false)
const searchQuery = ref('')
const filterCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框
const dialogVisible = ref(false)
const isEditing = ref(false)
const formRef = ref(null)
const submitting = ref(false)

const termForm = ref({
  id: null,
  term: '',
  category: '',
  definition: ''
})

// 表单验证规则
const formRules = {
  term: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择类别', trigger: 'change' }],
  definition: [{ required: true, message: '请输入释义', trigger: 'blur' }]
}

// 计算属性
const categories = computed(() => {
  const cats = [...new Set(terms.value.map(t => t.category))]
  return cats.sort()
})

const filteredTerms = computed(() => {
  let result = terms.value

  // 类别筛选
  if (filterCategory.value) {
    result = result.filter(t => t.category === filterCategory.value)
  }

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(
      t =>
        t.term.toLowerCase().includes(query) ||
        t.definition.toLowerCase().includes(query)
    )
  }

  return result
})

const displayedTerms = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTerms.value.slice(start, end)
})

const totalCount = computed(() => filteredTerms.value.length)

// 方法
const loadTerms = async () => {
  loading.value = true
  try {
    const response = await api.get('/dictionary')
    if (response.success) {
      terms.value = response.terms
    }
  } catch (error) {
    console.error('加载词典失败:', error)
    ElMessage.error('加载词典失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  isEditing.value = false
  termForm.value = {
    id: null,
    term: '',
    category: '',
    definition: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditing.value = true
  termForm.value = { ...row }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true

  try {
    let response
    if (isEditing.value) {
      response = await api.put(`/dictionary/${termForm.value.id}`, termForm.value)
    } else {
      response = await api.post('/dictionary', termForm.value)
    }

    if (response.success) {
      ElMessage.success(isEditing.value ? '词条已更新' : '词条已添加')
      dialogVisible.value = false
      loadTerms()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败：' + (error.response?.message || error.message))
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除词条"${row.term}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await api.delete(`/dictionary/${row.id}`)
    if (response.success) {
      ElMessage.success('词条已删除')
      loadTerms()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handlePageChange = () => {
  // 页码变化时，表格会自动更新
}

const getCategoryTagType = (category) => {
  const typeMap = {
    '设备名称': 'primary',
    '故障类型': 'warning',
    '性能参数': 'success',
    '工艺流程': 'info',
    '技术指标': 'danger'
  }
  return typeMap[category] || ''
}

onMounted(() => {
  loadTerms()
})
</script>

<style scoped>
.dictionary-page {
  padding: 0;
  width: 100%;
  max-width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header h3 {
  margin: 0;
  font-family: var(--font-family);
  font-size: var(--font-size-xl);
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-card) {
  border-radius: var(--radius-lg) !important;
  box-shadow: var(--shadow-sm) !important;
}

:deep(.el-card__body) {
  padding: var(--spacing-2xl) !important;
}

:deep(.el-table) {
  font-family: var(--font-family);
}

:deep(.el-button) {
  font-family: var(--font-family);
}

:deep(.el-input__inner) {
  font-family: var(--font-family);
}

:deep(.el-form-item__label) {
  font-family: var(--font-family);
  font-weight: 500;
  color: var(--text-primary);
}
</style>

